package com.android.bookgarden.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Window;
import android.widget.Toast;

import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.WXLoginBean;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.ui.BundTellActivity;
import com.android.bookgarden.ui.ShareActivity;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.LoadingDialog;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Create by zouqh
 * on 2018/12/11
 **/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler,RealtConstract.View {
    private static final String APP_SECRET = "9569c038231281a58df55939fb0daad1";
    private IWXAPI mWeixinAPI;
    public static final String WEIXIN_APP_ID = "wx153a5225a71797fb";
    private static String uuid;

    private RealtConstract.Presenter presenter;
    private WXLoginBean loginBean;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mWeixinAPI = WXAPIFactory.createWXAPI(this, WEIXIN_APP_ID, true);
        mWeixinAPI.handleIntent(this.getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWeixinAPI.handleIntent(intent, this);//必须调用此句话
    }

    //微信发送的请求将回调到onReq方法
    @Override
    public void onReq(BaseReq req) {
        LogUtil.e("aaaaaaaaaa","onReq");
    }

    //发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {
        LogUtil.e("aaaaaaaaaa","onResp");
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                LogUtil.e("aaaaaaaaaa","ERR_OK");
                finish();
                if (null!=ShareActivity.shareActivity){
                    Toast.makeText(getApplicationContext(), "分享成功 ", Toast.LENGTH_SHORT).show();

                    ShareActivity.shareActivity.notifaiShere(0);
                    return;
                }
                //发送成功
                SendAuth.Resp sendResp = (SendAuth.Resp) resp;
                if (sendResp != null) {
                    presenter = new BasePersenter(this,WXEntryActivity.this);
                    String code = sendResp.code;
                    getAccess_token(code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                LogUtil.e("aaaaaaaaaa","ERR_USER_CANCEL");
                if (null!=ShareActivity.shareActivity){
                    Toast.makeText(getApplicationContext(), "分享取消 ", Toast.LENGTH_SHORT).show();

                    ShareActivity.shareActivity.notifaiShere(1);
                    return;
                }
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                finish();
                LogUtil.e("aaaaaaaaaa","ERR_AUTH_DENIED");
                if (null!=ShareActivity.shareActivity){
                    Toast.makeText(getApplicationContext(), "分享拒绝 ", Toast.LENGTH_SHORT).show();
                    ShareActivity.shareActivity.notifaiShere(1);
                    return;
                }
                //发送被拒绝
                break;
            default:
                //发送返回
                break;
        }

    }




    /**
     * 获取openid accessToken值用于后期操作
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + WEIXIN_APP_ID
                + "&secret="
                + APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        LogUtil.e("getAccess_token",""+path);
        Map<String,String> map=null;

        presenter.loadData(map,"",path,1001);

//        //网络请求，根据自己的请求方式
//        VolleyRequest.get(this, path, "getAccess_token", false, null, new VolleyRequest.Callback() {
//            @Override
//            public void onSuccess(String result) {
//                LogUtils.log("getAccess_token_result:" + result);
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(result);
//                    String openid = jsonObject.getString("openid").toString().trim();
//                    String access_token = jsonObject.getString("access_token").toString().trim();
//                    getUserMesg(access_token, openid);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onError(String errorMessage) {
//
//            }
//        });
    }


    /**
     * 获取微信的个人信息
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        Map<String,String> map=null;
//        LoadingDialog.showMassge(this,"登录中...");
        presenter.loadData(map,"",path,1002);
//        LogUtils.log("getUserMesg：" + path);
//        //网络请求，根据自己的请求方式
//        VolleyRequest.get(this, path, "getAccess_token", false, null, new VolleyRequest.Callback() {
//            @Override
//            public void onSuccess(String result) {
//                LogUtils.log("getUserMesg_result:" + result);
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(result);
//                    String nickname = jsonObject.getString("nickname");
//                    int sex = Integer.parseInt(jsonObject.get("sex").toString());
//                    String headimgurl = jsonObject.getString("headimgurl");
//
//                    LogUtils.log("用户基本信息:");
//                    LogUtils.log("nickname:" + nickname);
//                    LogUtils.log("sex:" + sex);
//                    LogUtils.log("headimgurl:" + headimgurl);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                finish();
//            }
//
//            @Override
//            public void onError(String errorMessage) {
//
//            }
//        });
    }

    @Override
    public void returnData(String data, int urlCode) {

        if (TextUtils.isEmpty(data)){
            return;
        }
        LogUtil.e("获取数据----",data);

        handler.obtainMessage(urlCode,data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        LoadingDialog.hideProgress();
        if (urlCode==1001){
            Toast.makeText(this,"授权失败",Toast.LENGTH_SHORT).show();
        }
        if (urlCode==1002){
            Toast.makeText(this,"获取用户信息失败",Toast.LENGTH_SHORT).show();
        }

    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            switch (msg.what){
                case 1001:
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(data);
                        String openid = jsonObject.getString("openid").toString().trim();
                        String access_token = jsonObject.getString("access_token").toString().trim();
                        getUserMesg(access_token, openid);
                    } catch (JSONException e) {
                        LoadingDialog.hideProgress();
                        e.printStackTrace();
                    }
                    break;

                case 1002:
                    try {
                        jsonObject = new JSONObject(data);
                        String nickname = jsonObject.getString("nickname");
                        int sex = Integer.parseInt(jsonObject.get("sex").toString());
                        String headimgurl = jsonObject.getString("headimgurl");
                        String openid = jsonObject.getString("openid");
                        loginBean = new WXLoginBean();
                        loginBean.setHeadimgurl(headimgurl);
                        loginBean.setNickname(nickname);
                        loginBean.setOpenid(openid);
                        loginBean.setSex(sex+"");
                        LogUtil.e("用户基本信息:","");
                        LogUtil.e("nickname:" ,nickname);
                        LogUtil.e("sex:",  ""+sex);
                        LogUtil.e("headimgurl:", headimgurl);
                        checkUser(openid);
                    } catch (JSONException e) {
                        LoadingDialog.hideProgress();
                        e.printStackTrace();
                    }
                    break;
                case 1003:
                    DataBean bean = Utlis.getDataBean(data);
                    LoadingDialog.hideProgress();
                    if (bean.getCode()==200){

                    }else{
                        finish();
                        Bundle bundle =new Bundle();
                        bundle.putSerializable("wx",loginBean);
                        Intent intent = new Intent(WXEntryActivity.this, BundTellActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent );
                    }
                    break;
            }
        }
    };

    private void checkUser(String openid){
        Map<String,String> map=new HashMap<>();

        presenter.loadData(map,"", Apis.WX_LOGIN_URL+openid,1003);
    }
}

